package liwen.zhao;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;

import java.io.*;

public class MainPanel  extends Application {
    private Stage mainStage;
    public TextField editTextOfFileDriectory;//子文件路径
    public TextField fileNamePrefix;//通用文件名前缀
    public TextField postFix1;//文件名后缀1
    public TextField postFix2;//文件名后缀2
    public TextField finalPostFix;//最终后缀
    public TextField editTextToFilePath;//文件生成位置
    public TextField createFileName;//生成的文件名

    private File fileOFToFilePath;
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        this.mainStage=primaryStage;
        primaryStage.setTitle("文件合并");
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getClassLoader().getResource("resources/main.fxml"));
        VBox vbox = loader.<VBox>load();
        Scene scene = new Scene(vbox);
        primaryStage.setScene(scene);
        primaryStage.show();

    }
    public void startAppendFile(MouseEvent mouseEvent) {
        if(null==postFix1||null==postFix2||null==fileNamePrefix){
            createAlert(Alert.AlertType.WARNING,"文件前后缀相关字段不能为空！");
            return;
        }
        //获取文件的开始后缀和结束后缀的数值
        int start=0;
        int end=0;
        try{
            start=Integer.parseInt(postFix1.getText());
            end=Integer.parseInt(postFix2.getText());
        }catch (Exception e){
            createAlert(Alert.AlertType.ERROR,e.getMessage());
            return;
        }
        if("".equals(editTextToFilePath.getText())||"".equals(createFileName.getText())){
            createAlert(Alert.AlertType.ERROR,"生成的文件名和输出路径不能为空！");
            return;
        }
        //生成文件
        FileOutputStream fileOutputStream=null;
        try {
            fileOutputStream =new FileOutputStream(editTextToFilePath.getText()+"\\"+createFileName.getText());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //拼接文件
        FileInputStream fileInputStream=null;
        for(int i=start;i<=end;i++){
            String fstart="0";
            if(i<10){
                fstart=fstart+i;
            }else{
                fstart=i+"";
            }
            File file;
            file=new File(editTextOfFileDriectory.getText()+"\\"+fileNamePrefix.getText()+fstart+finalPostFix.getText());//DAY00.xxx
            fileInputStream = appendFile(fileOutputStream, fileInputStream, file);
            //额外文件的处理
            if(i==20){
                file=new File(editTextOfFileDriectory.getText()+"\\"+fileNamePrefix.getText()+fstart+"Plus"+finalPostFix.getText());
                fileInputStream = appendFile(fileOutputStream, fileInputStream, file);
            }

        }

        //关闭文件输出流
        try {
            fileOutputStream.close();
        } catch (IOException e) {
            fileOutputStream=null;
            e.printStackTrace();
        }
        createAlert(Alert.AlertType.INFORMATION,"完成！");

    }

    private FileInputStream appendFile(FileOutputStream fileOutputStream, FileInputStream fileInputStream, File file) {
        if(!file.exists()){//如果文件不存在继续
            createAlert(Alert.AlertType.WARNING,file.getName()+" 不存在，点击确定继续！");
            return fileInputStream;
        }
        try {
            fileInputStream =new FileInputStream(file);
            byte[] bytes=new byte[1024];
            int r;
            while ((r=fileInputStream.read(bytes))!=-1){
                fileOutputStream.write(bytes,0,r);
            }
            //最后加一个回车换行
            fileOutputStream.write("\n".getBytes());
            fileOutputStream.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                fileInputStream=null;
            }
        }
        return fileInputStream;
    }

    public void fileChoiseLocation(MouseEvent mouseEvent) {
        DirectoryChooser directoryChooser=new DirectoryChooser();
        File file=directoryChooser.showDialog(mainStage);
        if(editTextOfFileDriectory!=null){
            editTextOfFileDriectory.setText(file.getPath());
        }

    }

    public void fileCreateLocation(MouseEvent mouseEvent) {
        DirectoryChooser directoryChooser=new DirectoryChooser();
        File file=directoryChooser.showDialog(mainStage);
        if(editTextToFilePath!=null){
            editTextToFilePath.setText(file.getPath());
        }

        /*FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Open Resource File");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("MarkDown文件或其他文本文件", "*.md","."));
        fileOFToFilePath = fileChooser.showOpenDialog(mainStage);*/
    }

    //提示框
    protected Alert createAlert(Alert.AlertType alertType, String showText) {
        Alert alert = new Alert(alertType, "");
        alert.initModality(Modality.APPLICATION_MODAL);
        alert.initOwner(mainStage);
        alert.getDialogPane().setContentText(showText);
        alert.getDialogPane().setHeaderText(null);
        alert.showAndWait()
                .filter(response -> response == ButtonType.OK)
                .ifPresent(response -> System.out.println("The alert was approved"));
        return alert;
    }
}
